package cc.liyinghao.springsecuritydemo.controller;


import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.security.core.Authentication;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Controller
@Tag(name = "限流接口")
public class LimitController {
    private static final ConcurrentHashMap<String, AtomicInteger> requestCounts = new ConcurrentHashMap<>();

    @GetMapping("/secure-test")
    public String testSecurityRateLimit(Authentication authentication) {
        String username = authentication.getName();
        requestCounts.putIfAbsent(username, new AtomicInteger(0));
        int count = requestCounts.get(username).incrementAndGet();
        if (count > 3) {
            return "请求过多，请稍后再试！";
        }
        return "请求成功";
    }

    // 每分钟清理一次请求计数
    @Scheduled(fixedRate = 5000)
    public void resetRequestCounts() {
        requestCounts.clear();
    }
}
